package com.swing.trial;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import net.miginfocom.swing.MigLayout;

import com.workoutdiary.dao.UserDao;
import com.workoutdiary.entities.User;
import com.workoutdiary.service.Logger;

public class LoginFrame {

	private JFrame frame;
	private JTextField textFieldLogin;
	private JTextField textFieldPassword;
	private JButton btnSubmit;
	private JButton buttonCancel;

	private FormListener formListener;
	private TableListener tableListener;
	
	public void setFormListener(FormListener listener) {
		this.formListener = listener;
	}
	
	public void setTableListener(TableListener listener) {
		this.tableListener = listener;
	}
	
	public void show() {
		frame.setVisible(true);
	}

	public void hide() {
		frame.setVisible(true);
	}
	
	public LoginFrame() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setTitle("Login");
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(new MigLayout("", "[104.00][199.00,grow][58.00]", "[40.00][][39.00][19.00][41.00][53.00]"));
		
		JLabel lblNewLabel = new JLabel("Login");
		frame.getContentPane().add(lblNewLabel, "cell 0 1,alignx right");
		
		textFieldLogin = new JTextField();
		frame.getContentPane().add(textFieldLogin, "cell 1 1,growx");
		textFieldLogin.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("Password");
		frame.getContentPane().add(lblNewLabel_1, "cell 0 2,alignx trailing");
		
		textFieldPassword = new JTextField();
		frame.getContentPane().add(textFieldPassword, "cell 1 2,growx");
		textFieldPassword.setColumns(10);
		
		btnSubmit = new JButton("Submit");
		frame.getContentPane().add(btnSubmit, "flowx,cell 1 4");
		
		buttonCancel = new JButton("Cancel");
		buttonCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				hide();
			}
		});
		frame.getContentPane().add(buttonCancel, "cell 1 4");
		
		JButton btnAddNew = new JButton("Add New");
		frame.getContentPane().add(btnAddNew, "cell 1 4");
		
		setActions();
	}
	
	private void setActions() {
		btnSubmit.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				Logger loger = new Logger();
				String login = textFieldLogin.getText();
				String password = textFieldPassword.getText();
				User user = loger.login(login, password);
				if(user != null) {
					formListener.loggedIn(user);
					System.out.println("LOGGED IN");
					hide();
				} else {
					textFieldLogin.setText("wrong");
					textFieldPassword.setText("wrong");
				}
			}
		});
	}

}
